package com.xwj.service.impl;

import com.alibaba.fastjson.JSON;
import com.xwj.service.ProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProducerServiceImpl implements ProducerService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public SendResult syncSendMsg(String msg) {
        SendResult sendResult = rocketMQTemplate.syncSend("syncSendMsg_topic", MessageBuilder.withPayload(msg).build());
        log.info("发送结果：{}", JSON.toJSONString(sendResult));
        return sendResult;
    }

    @Override
    public void asyncSendMsg(String msg) {
        rocketMQTemplate.asyncSend("asyncSendMsg_topic", MessageBuilder.withPayload(msg).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送成功：{}", JSON.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("发送失败：{}", throwable.getMessage());
            }
        });
    }

    @Override
    public void asyncSendOrderly(String msg, String hashKey) {
        rocketMQTemplate.asyncSendOrderly("asyncSendOrderly_topic", MessageBuilder.withPayload(msg).build(), hashKey, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("顺序发送成功：{}", JSON.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("顺序发送失败：{}", throwable.getMessage());
            }
        });
    }

    @Override
    public void asyncSendMsgWithTag(String msg, String tag) {
        rocketMQTemplate.asyncSend("asyncSendMsgWithTag_topic" + ":" + tag, MessageBuilder.withPayload(msg).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送成功：{}", JSON.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("发送失败：{}", throwable.getMessage());
            }
        });
    }

    @Override
    public void oneWaySendMsg(String msg) {
        rocketMQTemplate.sendOneWay("oneWaySendMsg_topic", MessageBuilder.withPayload(msg).build());
    }
}
